package com.alibaba.csp.sentinel.dashboard.rule.convert;


import com.alibaba.csp.sentinel.adapter.gateway.common.rule.GatewayFlowRule;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.gateway.GatewayFlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.FlowRuleEntity;
import com.alibaba.csp.sentinel.dashboard.datasource.entity.rule.RuleEntity;
import com.alibaba.csp.sentinel.dashboard.discovery.AppInfo;
import com.alibaba.csp.sentinel.dashboard.discovery.MachineInfo;
import com.alibaba.csp.sentinel.datasource.Converter;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.fastjson.JSON;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author: shaozeming
 * @date: 2022/8/12 16:44
 * @description:
 **/
public class GetawayRuleConverter implements RuleConverter{

    @Override
    public Converter<List<RuleEntity>, String> ruleEntityEncoder(){
        return v-> JSON.toJSONString(v.stream().map(entity-> ((GatewayFlowRuleEntity)entity).toGatewayFlowRule()).collect(Collectors.toList()));
    }

    @Override
    public Converter<String, List<RuleEntity>> ruleEntityDecoder(AppInfo appInfo) {
        ArrayList<MachineInfo> machineList = new ArrayList<>(appInfo.getMachines());
        return s -> Optional.ofNullable(s)
                .map(rules -> JSON.parseArray(rules, GatewayFlowRule.class))
                .map(rules -> rules.stream()
                        .map(e ->(RuleEntity) GatewayFlowRuleEntity.fromGatewayFlowRule(appInfo.getApp(),machineList.get(0).getIp(),machineList.get(0).getPort(),e))
                        .collect(Collectors.toList()))
                .orElse(null);
    }
}
